package com.app.couponsharelife.ui.main.home.shopweb

import android.content.ActivityNotFoundException
import android.content.Intent
import android.view.View
import android.webkit.*
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TBBandRealtionBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_webview.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.net.URISyntaxException
import java.util.HashMap

/**
 *Created by xct on 2019/1/17
 *Description:
 */
class WebActivity:BaseActivity() {
    private var name=""
    private var url=""
    private var webChromeClient: WebChromeClient?=null
    private var webViewClient:WebViewClient?=null
    override val viewLayoutId: Int
        get() = R.layout.activity_webview

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        url=intent!!.getStringExtra("url")?:""
        name=intent!!.getStringExtra("name")?:""
        tvToolBarTitle.text = name
        ivBack.setOnClickListener {onBackPressed()}
        ivFinish.setOnClickListener { finish() }
        showProgressDialog("请稍候")
        webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress == 100) {
                    dismissProgressDialog()
                    web_webview.visibility = View.VISIBLE
                }
                super.onProgressChanged(view, newProgress)
            }
        }
        web_webview.webChromeClient=webChromeClient
        webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(p0: WebView?, url: String?): Boolean {
                if (url!=null&&url.isNotEmpty()){
                    if (url.startsWith("http") || url.startsWith("https") || url.startsWith("ftp")){
                        //Log.e("eee","常规链接---->${url}")
                        //http://127.0.0.1:12345/error?code=fdWuTuXdwFgZHQ8smRnueUlB4290749&state=1212
                        if (url.startsWith("http://127.0.0.1:12345")){
                            val arr=url.split("code=")
                            if (arr.size>1){
                                val arr1=arr[1].split("&")
                                if (arr1.size>1){
                                    val code=arr1[0]?:""
                                    if (code.isNotEmpty()){
                                        bindRlId(code)
                                    }
                                }
                            }
                            return true
                        }else{
                            return super.shouldOverrideUrlLoading(p0, url)
                        }
                    }else{
                        if (url.startsWith("tbopen://")){
                            return true
                        }else{
                            //Log.e("eee","AppUri---->${url}")
                            var intent: Intent?=null
                            try {
                                intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
                            } catch (e: URISyntaxException) {
                                return false
                            }
                            intent.setComponent(null)
                            try {
                                startActivity(intent)
                            } catch (e: ActivityNotFoundException) {
                                return false
                            }
                            return true
                        }
                    }
                }else{
                    return super.shouldOverrideUrlLoading(p0, url)
                }
            }
        }
        web_webview.webViewClient=webViewClient
        val webSettings=web_webview.settings
        webSettings!!.allowFileAccess = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        webSettings.useWideViewPort = true
        webSettings.setSupportMultipleWindows(false)
        // webSetting.setLoadWithOverviewMode(true);
        webSettings.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSettings.domStorageEnabled = true
        webSettings.javaScriptEnabled = true
        webSettings.setGeolocationEnabled(true)
        webSettings.setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
        webSettings.setAppCachePath(this.getDir("appcache", 0).path)
        webSettings.databasePath = this.getDir("databases", 0).path
        webSettings.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .path)
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSettings.pluginState = WebSettings.PluginState.ON_DEMAND
        if (name=="淘宝授权"){
            val map = HashMap<String, String>()
            val page = AlibcPage(url)
            val showParams = AlibcShowParams(OpenType.H5, false)
            AlibcTrade.show(this,web_webview,webViewClient!!,webChromeClient!!,page,showParams,null,map,object : AlibcTradeCallback {
                override fun onFailure(p0: Int, p1: String?) {

                }

                override fun onTradeSuccess(p0: AlibcTradeResult?) {
                    //Log.i("eee", "获取淘宝用户信息: ")
                }
            })
        }else {
            web_webview.loadUrl(url)
        }
    }
    private fun bindRlId(code:String){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        map["code"]=code
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.bandRealtion(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<TBBandRealtionBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<TBBandRealtionBean>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            AppUtils.setString(Contacts.ADZONE_ID, it.data!!.relationId?:"")
                            showToastMsg("授权绑定成功！")
                            finish()
                        }else{
                            showToastMsg("授权绑定失败！")
                            finish()
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错！")
                        }
                        finish()
                    }
                })
    }
    override fun onBackPressed() {
        if (web_webview.canGoBack()) {
            web_webview.goBack()
        } else {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}